minetest.register_chatcommand("apropriar", {
	params = "<Jogador> <X1,Y1,Z1> <X2,Y2,Z2>",
	description = "Protege um terreno pertencente a um jogador. Nao pode colidir com outros terrenos.",
	privs = {privs=true},
	func = function(name, param)
		--if not minetest.get_player_privs(name)["privs"] then
		--	minetest.chat_send_player(name, "Voce nao tem permissao para fazer isso.")
		--	return true -- Handled chat message
		--end
		local ownername, sx, sy, sz, ex, ey, ez = string.match(param, "(.-) ([0-9%-]-)%,([0-9%-]-)%,([0-9%-]-) ([0-9%-]-)%,([0-9%-]-)%,([0-9%-]*)")
		if ownername == nil or string.len(ownername) == 0
			or sx == nil or string.len(sx) == 0
			or sy == nil or string.len(sy) == 0
			or sz == nil or string.len(sz) == 0
			or ex == nil or string.len(ex) == 0
			or ey == nil or string.len(ey) == 0
			or ez == nil or string.len(ez) == 0
		then
			minetest.chat_send_player(name, "Sintaxe: /apropriar <Nome do Jogador> <Posicao Inicial> <Posicao Final>")
			return true -- Handled chat message
		end
		local player = minetest.env:get_player_by_name(ownername)
		if player == nil then
			minetest.chat_send_player(name, 'ERRO: Jogador nao existe ou nao esta online.')
			--print("Jogador Inexistente!")
			return true -- Handled chat message
		end
		print("[lunonodes] PROPRIAcaO: proprietario='" .. ownername .. "' Inicio='" .. sx .. "," .. sy .. "," .. sz .. "' Fim='" .. ex .. "," .. ey .. "," .. ez.."'")

		sx = tonumber(sx)
		sy = tonumber(sy)
		sz = tonumber(sz)

		ex = tonumber(ex)
		ey = tonumber(ey)
		ez = tonumber(ez)

		if (CheckCollisions({x=sx,y=sy,z=sz}, {x=ex,y=ey,z=ez})) == true then
			minetest.chat_send_player(name, "As areas proprietarias colidiram!")
			return true -- Handled chat message
		end	
		
		minetest.sound_play("sound_doorbell", {pos=player:getpos(), max_hear_distance = 1})
		minetest.chat_send_player(ownername, ownername.." recebeu o terreno numero "..(table.maxn(owner_defs)+1).." entre {["..sx..","..sy..","..sz.."]~["..ex..","..ey..","..ez.."]}.")
		--minetest.chat_send_player(name, ownername.." recebeu o terreno numero "..(table.maxn(owner_defs)).." entre {["..sx..","..sy..","..sz.."]~["..ex..","..ey..","..ez.."]}.")
		table.insert(owner_defs, {x1=sx, y1=sy, z1=sz, x2=ex, y2=ey, z2=ez, owner=ownername})
		owner_defs[table.maxn(owner_defs)].id = table.maxn(owner_defs)
		table_save( owner_defs, owners_db_filename )

		return true -- Handled chat message
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("proteger", {
	params = "<Jogador> <X1,Y1,Z1> <X2,Y2,Z2>",
	description = "Simimar ao comando '/apropriar', mas permitite colisoes de terrenos.",
	privs = {privs=true},
	func = function(name, param)
		local new_ownername, sx, sy, sz, ex, ey, ez = string.match(param, "(.-) ([0-9%-]-)%,([0-9%-]-)%,([0-9%-]-) ([0-9%-]-)%,([0-9%-]-)%,([0-9%-]*)")
		if new_ownername == nil or string.len(new_ownername) == 0
		or sx == nil or string.len(sx) == 0
		or sy == nil or string.len(sy) == 0
		or sz == nil or string.len(sz) == 0
		or ex == nil or string.len(ex) == 0
		or ey == nil or string.len(ey) == 0
		or ez == nil or string.len(ez) == 0
		then
			minetest.chat_send_player(name, "Sintaxe: /proteger <Nome do Jogador> <Posicao Inicial> <Posicao Final>")
			return true -- Handled chat message
		end
		local player = minetest.env:get_player_by_name(new_ownername)

		if player == nil then
			minetest.chat_send_player(name, "O jogador '"..new_ownername.."' precisa estar online para receber a protecao de area.")
			return true -- Handled chat message
		end

		--print(cmd.." invoked, new_ownername=" .. new_ownername .. " startpos=" .. sx .. "," .. sy .. "," .. sz .. " endpos=" .. ex .. "," .. ey .. "," .. ez)
		--print("PROTEcaO: proprietario=" .. new_ownername .. " Inicio=" .. sx .. "," .. sy .. "," .. sz .. " Fim=" .. ex .. "," .. ey .. "," .. ez)

		sx = tonumber(sx)
		sy = tonumber(sy)
		sz = tonumber(sz)

		ex = tonumber(ex)
		ey = tonumber(ey)
		ez = tonumber(ez)

		area_pos1 = {x=sx, y=sy, z=sz}
		area_pos2 = {x=ex, y=ey, z=ez}

		p=nil

		--Look to see if this new area is inside an area owned by the player using this function
		for n,def in pairs(owner_defs) do
			if (area_pos1.x >= def.x1 and area_pos1.x <= def.x2 or
				area_pos1.x <= def.x1 and area_pos1.x >= def.x2) and
				(area_pos2.x >= def.x1 and area_pos2.x <= def.x2 or
				area_pos2.x <= def.x1 and area_pos2.x >= def.x2) then
		
				if (area_pos1.y >= def.y1 and area_pos1.y <= def.y2 or
					area_pos1.y <= def.y1 and area_pos1.y >= def.y2) and
					(area_pos2.y >= def.y1 and area_pos2.y <= def.y2 or
					area_pos2.y <= def.y1 and area_pos2.y >= def.y2) then
			
					if (area_pos1.z >= def.z1 and area_pos1.z <= def.z2 or
						area_pos1.z <= def.z1 and area_pos1.z >= def.z2) and
						(area_pos2.z >= def.z1 and area_pos2.z <= def.z2 or
						area_pos2.z <= def.z1 and area_pos2.z >= def.z2) then
				
						--OK, found entry that has both area_poss
						if def.owner == name then
							p=def.id
							break
						end
					end
				end
			end
		end

		if p == nil then
			minetest.chat_send_player(name, "Voce nao tem permissao para fazer isso.")
			return true -- Handled chat message
		end

		minetest.sound_play("sound_doorbell", {pos=player:getpos(), max_hear_distance = 1})
		minetest.chat_send_player(new_ownername, new_ownername.." recebeu o terreno numero "..(table.maxn(owner_defs)+1).." entre {["..sx..","..sy..","..sz.."]~["..ex..","..ey..","..ez.."]}.")
		table.insert(owner_defs, {x1=sx, y1=sy, z1=sz, x2=ex, y2=ey, z2=ez, owner=new_ownername})
		if p ~= nil then
			owner_defs[table.maxn(owner_defs)].parent = p
		end
		owner_defs[table.maxn(owner_defs)].id = table.maxn(owner_defs)
		table_save( owner_defs, owners_db_filename )

		return true -- Handled chat message
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("listar", {
	params = "",
	description = "Lista todos os IDs de terrenos protegidos. Necessita do privilegio 'privs', caso contrario exibira somente os terrenos pertecentes ao executor do comando.",
	privs = {},
	func = function(name, param)
		show_all = false
		if minetest.get_player_privs(name)["privs"] then
			show_all = true
			minetest.chat_send_player(name, "Exibindo todas as propriedades declaradas:")
			for n,def in pairs(owner_defs) do
				entry = def.id .. ": " .. def.owner .. " (" .. def.x1 .. "," .. def.y1 .. "," .. def.z1 .. ") (" .. def.x2 .. "," .. def.y2 .. "," .. def.z2 .. ")"
				if def.parent ~= nil then
					entry = entry .. " parent: " .. def.parent
				end
				minetest.chat_send_player(name, entry)
			end
		else
			--minetest.chat_send_player(name, "Showing your owner entries (You can delete only these)")
			minetest.chat_send_player(name, "Mostrando suas propriedades declaradas (Voce pode excluir apenas estas)")
			for n,def in pairs(owner_defs) do
				if def.owner == name then
					entry = def.id .. ": " .. def.owner .. " (" .. def.x1 .. "," .. def.y1 .. "," .. def.z1 .. ") (" .. def.x2 .. "," .. def.y2 .. "," .. def.z2 .. ")"
					if def.parent ~= nil then
						entry = entry .. " parent: " .. def.parent
					end
					minetest.chat_send_player(name, entry)
					for n,defc in pairs(owner_defs) do
						if defc.parent == def.id then
							entry = "->" .. defc.id .. ": " .. defc.owner .. " (" .. defc.x1 .. "," .. defc.y1 .. "," .. defc.z1 .. ") (" .. defc.x2 .. "," .. defc.y2 .. "," .. defc.z2 .. ")"
							if defc.parent ~= nil then
								entry = entry .. " parent: " .. defc.parent
							end
							minetest.chat_send_player(name, entry)
						end
					end
				end
			end
		end
		return true -- Handled chat message
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("desproteger", {
	params = "<numero da Declaracao>",
	description = "Desprotege terreno. So sera executado pelo proprietario original, ou por alguem que possua o privilegio 'privs'.",
	privs = {},
	func = function(name, param)
		your_ids = {}
		for n,def in pairs(owner_defs) do
			if def.owner == name or minetest.get_player_privs(name)["privs"] then
				table.insert(your_ids, def.id)
				for n,defc in pairs(owner_defs) do
					if defc.parent == def.id then
						table.insert(your_ids, defc.id)
					end
				end
			end
		end
		--local e = string.match(message, param.." (.*)")
		local e = string.match(param, "(.*)")

		if e == nil or string.len(e) == 0 then
			minetest.chat_send_player(name, "sintaxe: /desproteger <numero  da Declaracao>")
			return true -- Handled chat message
		end
		
		e = tonumber(e)
		found = false
		for _,k in pairs(your_ids) do
			if k == e then 
				RemoveTableEntry(e)
				table_save( owner_defs, owners_db_filename )
				return true -- Handled chat message
			end
		end
		return true -- Handled chat message
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("transferir", {
	params = "<numero  da Declaracao> <Novo Propriertario>",
	description = "Transfere terreno. So sera executado pelo proprietario original, ou por alguem que possua o privilegio 'privs'.",
	privs = {},
	func = function(name, param)
		your_ids = {}
		for n,def in pairs(owner_defs) do
			if def.owner == name or minetest.get_player_privs(name)["privs"] then
				table.insert(your_ids, def.id)
				for n,defc in pairs(owner_defs) do
					if defc.parent == def.id then
						table.insert(your_ids, defc.id)
					end
				end
			end
		end
	
		local e, new_owner = string.match(param, "(.-) (.*)")
	
		if e == nil or new_owner == nil or string.len(e) == 0 or string.len(new_owner) == 0 then
			minetest.chat_send_player(name, 'Sintaxe: /transferir <numero  da Declaracao> <Novo Propriertario>')
			minetest.chat_send_player(name, 'Digite [/listar] para ver suas declaracoes')
			return true -- Handled chat message
		end
	
		--[[local player = minetest.env:get_player_by_name(new_owner)
		if player == nil then
			--print("new_owner is nil")
			print("O novo propriertario deste terreno nao esta online para receber a propriedade.")
			return true -- Handled chat message
		end--]]
		
		e = tonumber(e)
		found = false
		for _,k in pairs(your_ids) do
			if k == e then 
				for n,def in pairs(owner_defs) do
					if def.id == e then
						minetest.chat_send_player(name, "A propriedade numero "..def.id.." de '"..owner_defs[n].owner.."' foi transferida para '"..new_owner.."'.")
						owner_defs[n].owner = new_owner
						table_save( owner_defs, owners_db_filename )
						return true -- Handled chat message
					end
				end
			
			end
		end
		return true -- Handled chat message
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("alertowner", {
	params = "<true/false>",
	description = "Alerta ao proprietario de um terreno quando outro jogador esta tentando alterar seu territorio.",
	privs = { },
	func = function(name, param)
		if param=="true" or param=="false" then
			if minetest.get_player_privs(name)["privs"] then
				minetest.setting_set("lunonodes_alertowner",param) 
				minetest.chat_send_player(name, "lunonodes_alertowner = '"..param.."'.")
			else
				minetest.chat_send_player(name, "Voce nao tem o privilegio 'privs' para usar este comando.")
			end
		else
			minetest.chat_send_player(name, "Sintaxe: /alertowner <true/false>")
		end
	end,
})

--#####################################################################################################################################

minetest.register_chatcommand("lunonodes", {
	params = "",
	description = "Exibe todos os comando deste mod",
	privs = {},
	func = function(name, param)
		--local player = minetest.get_player_by_name(name)
		--if player == nil then
			--print("Falha de ajuda: Player solicitante nao encontrado.")
			--return true -- Handled chat message
		--end
		minetest.chat_send_player(name, "    ", false)
		minetest.chat_send_player(name, "############################################################################################", false)
		minetest.chat_send_player(name, "### LUNONODES (TELA DE AJUDA DESTE MODING)                                               ###", false)
		minetest.chat_send_player(name, "### Desenvolvedor:'Lunovox Heavenfinder'<rui.gravata@gmail.com>                          ###", false)
		minetest.chat_send_player(name, "### (Inclui traducoes dos mod: Node_ownership                                            ###", false)
		minetest.chat_send_player(name, "############################################################################################", false)
		minetest.chat_send_player(name, "COMANDOS:", false)
		minetest.chat_send_player(name, "   * /apropriar <Jogador> <X1,Y1,Z1> <X2,Y2,Z2>", false)
		minetest.chat_send_player(name, "       (Protege um terreno pertencente a um jogador. Nao pode colidir com outros terrenos.", false)
		minetest.chat_send_player(name, "       Necessita do privilegio 'privs'.)", false)
		minetest.chat_send_player(name, "   * /proteger <Jogador> <X1,Y1,Z1> <X2,Y2,Z2>", false)
		minetest.chat_send_player(name, "       (Simimar ao comando '/apropriar' mas permitite colisoes de terrenos.", false)
		minetest.chat_send_player(name, "       Necessita do privilegio 'privs'.)", false)
		minetest.chat_send_player(name, "   * /listar", false)
		minetest.chat_send_player(name, "       (Lista todos os IDs de terrenos protegidos. Necessita do privilegio 'privs', caso", false)
		minetest.chat_send_player(name, "       contrario exibira somente os terrenos pertecentes ao executor do comando.)", false)
		minetest.chat_send_player(name, "   * /desproteger <TerrenoID>", false)
		minetest.chat_send_player(name, "       (Desprotege terreno. So sera executado pelo proprietario original, ou por alguem que", false)
		minetest.chat_send_player(name, "       possua o privilegio 'privs'.)", false)
		minetest.chat_send_player(name, "   * /transferir <TerrenoID> <NovoProprietario>", false)
		minetest.chat_send_player(name, "       (Transfere o direito de terreno para outro jogador. So sera executado pelo proprietario", false)
		minetest.chat_send_player(name, "       original, ou por alguem que possua o privilegio 'privs'.)", false)
		minetest.chat_send_player(name, "   * /alertowner <true/false>", false)
		minetest.chat_send_player(name, "       (Ativa e Desativa o alerta ao proprietario quando um terreno quando outro jogador esta", false)
		minetest.chat_send_player(name, "       tentando alterar seu territorio.)", false)
		minetest.chat_send_player(name, "############################################################################################", false)
		minetest.chat_send_player(name, name..", precione F10 e use a rolagem do mouse para ler todo este tutorial!!!", false)
	end,
})
